<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
    </head>
    <body>
        <div>
        登陆
        <form onsubmit="login(this);return false;" autocomplete="off">
            <input type="text" name="username" oninput="cacheInput(this);" placeholder="用户名" required>
            <input type="password" name="passwd" oninput="cacheInput(this);" placeholder="密码" required>
            <input type="submit" value="登录">
            <input type="button" value="注册" onclick="newdata()">
        </form>
        </div>
    </body>
    <script>
        let loginfo = {
          username : '',
          passwd : ''
        }
    
        function cacheInput (t) {
          if (t.name === 'username') {
            loginfo.username = t.value.trim()
            console.log(loginfo.username)
          } else if (t.name === 'passwd') {
            loginfo.passwd = t.value
            console.log(loginfo.passwd)
            console.log(JSON.stringify(loginfo))
          }
        }

        function login(t) {
          console.log(t);
          if (loginfo.username === '' || loginfo.passwd === '') {
            return
          }
    
          fetch('/data', {
            method : 'POST',
            headers : {
              'content-type' : 'application/json'
            },
            body : JSON.stringify(loginfo)
          }).then(res => res.json()).catch(err => {
            alert(err.message)
          }).then(response => {
            if(response.status === 'success'){
              location.href = '/login';
              console.log(response)
            }else{
              alert('用户名或密码错误')
            }
          });

        }
        
        function newdata(){
          fetch('/new')
          .then(res =>location.href = '/new')
        }
      </script>
</html>
